//取消重复的异步请求
class CancelPromise{
    constructor(){
        //保留最后一次结果
        this.curPromise = {};
        this.reject ={};
        //防抖
        this.curPromiseTimer={};
        this.noFirstPromise = {}
        //节流
        this.nowPromise = null
    }
    //name用于标识同类型请求，丢弃重复内容
    request(name,promise){
        if(this.curPromise[name]){
            this.cancel(name);
        }
        let cancel = new Promise((resolve,reject)=>{
            this.reject[name] = reject;
        })
        this.curPromise[name] = Promise.race([promise,cancel]);
        return this.curPromise[name];
    }
    cancel(name){
        this.reject[name]("丢弃重复请求的内容");
    }
    //防抖取消重复请求
    debounce(name,fn,second = 200){
        let that = this
        if(!this.noFirstPromise[name]){
            that.noFirstPromise[name] = true; 
            this.curPromiseTimer[name] = setTimeout(()=>{
                fn().finally(()=>{
                    that.noFirstPromise[name] = false;              
                },0) 
            })            
        }
        else if(that.noFirstPromise[name] && this.curPromiseTimer[name]){       
            clearTimeout(this.curPromiseTimer[name]);
            this.curPromiseTimer[name] = setTimeout(()=>{
                fn().finally(()=>{
                    that.noFirstPromise[name] = false;
                });
            },second)
        }        
    }
    //节流操作
    throttle(promise){
    if(this.nowPromise) return
    return new Promise((resolve,reject)=>{
        this.nowPromise = promise;
        promise.then(res=>{
            resolve(res);
            this.nowPromise = null;
        })
    })
}
    
}

let cancelPromise = new CancelPromise();
export{
    cancelPromise
}